const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgBase: app.globalData.imgUrl,
    localImg: app.globalData.staticimgUrl,
    totalMoney: 0,
    calculateTotalMoney: '', // 订单总金额
    take: !1,
    takes: !0,
    carts: '',
    checkedcoin: false,
    maxCoin: '', // 美丽币
    maxPrice: '', // 抵用钱数
    goodsList: [], // 订单列表数据
    totalPrice: '', // 订单总金额
    consigneeid: "", //收货人的信息
    newvalue: "",
    invoice:'',      // 发票信息
    newchecked: !1,
    orderType: '',    // 订单类型
    valueMoney:'',
    coinShow:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function() {
    var that = this;
    if (app.globalData.consigneeid != "") {
      that.setData({
        takes: !1,
        take: !0,
        consigneeid: app.globalData.consigneeid,
        consigneename: app.globalData.consigneename,
        consigneephone: app.globalData.consigneephone,
        consigneeaddress: app.globalData.consigneeaddress,
      })
    }
  },
  onLoad: function(options) {
    const carts = options.carts;
    this.setData({
      carts
    })
    this.getOrderList();
    this.getAddress();
  },
  //获取订单列表
  getOrderList() {
    const that = this;
    const param = {
      cartgoods: this.data.carts
    }
    app.request({
      url: 'shopp/shoppcartApi/settlement',
      data: param,
      success: function(res) {
        that.setData({
          goodsList: res.data.goodsArray,
          totalPrice: res.data.totalPrice,
          calculateTotalMoney: res.data.totalPrice,
          orderType:1
        });
        that.beautifulCoin();
        wx.setStorageSync('totalPrice', res.data.totalPrice);
      },
      fail: function(res) {}
    });
  },
  //获取收货地址列表
  getAddress() {
    var that = this;
    app.request({
      url: 'shopp/orderConsigneeApi/getConsigneeArray',
      data: {},
      method: 'GET',
      success(res) {
        var array = res.data;
        for (var kk = 0; kk < array.length; kk++) {
          if (array[kk].isdefault == 1) {
            that.setData({
              consigneeid: array[kk].id,
              consigneename: array[kk].name,
              consigneephone: array[kk].mobile,
              consigneeaddress: array[kk].address,
              take: !0,
              takes: !1,
            })
          }
        }
      }
    })
  },
  //获取美丽币
  beautifulCoin() {
    const that = this;
    const totalPrice = this.data.totalPrice;
    app.request({
      url: "doctor/beautyCoin/getBeautyCoin",
      success: function(res) {
        const maxPrice = res.data.maxPrice;
        const maxCoin = res.data.maxCoin;
        const valueMoney = res.data.valueMoney;
        const result = maxCoin / maxPrice ;
        console.log(result)
        // 商品价格大于抵扣数
        if (totalPrice > maxPrice){
          that.setData({
            maxCoin: res.data.maxCoin,
            maxPrice: res.data.maxPrice
          })
        } else if (totalPrice <= maxPrice && totalPrice >= valueMoney){
         
          that.setData({
            maxCoin: result * parseInt(totalPrice),
            maxPrice: parseInt(totalPrice)
          })
        } else if (totalPrice < valueMoney){
          that.setData({
           coinShow: true
          })
        }
        // else {
        //   that.setData({
        //     maxCoin: res.data.maxCoin,
        //     maxPrice: res.data.maxPrice
        //   })
        // }
      },
      fail: function(res) {
        
      }
    });
  },
  //协议内容
  agreement: function() {
    var id = 9;
    wx.navigateTo({
      url: '../doctor-news-system/doctor-news-system?id=' + id,
    })
  },
  changeCoinChecked: function(e) {
    let {
      maxCoin
    } = this.data;
    if (Number(maxCoin) > 0) {
      let checked = !this.data.checkedcoin;
      this.setData({
        checkedcoin: checked
      });
      this.calculateTotalPrice();
    } else {
      wx.showToast({
        icon: 'none',
        title: '您的美丽币不足',
        duration: 1000
      });
    }
  },
  calculateTotalPrice: function() {
    let {
      totalPrice,
      maxPrice,
      checkedcoin,
    } = this.data;
    let total = Number(totalPrice);
    if (checkedcoin) {
      total = total - Number(maxPrice);
    }
    this.setData({
      calculateTotalMoney: total
    });
  },
  //点击同意协议
  checkboxChange: function(e) {
   
    this.setData({
      newvalue: e.detail.value[0]
    })
  },
  //提交订单
  submitRoder: function() {
    this.setData({
      invoice: wx.getStorageSync('invoice') 
    })
    const that = this;
    let {
      checkedcoin,
      maxPrice,
      totalPrice,
      calculateTotalMoney
    } = this.data;
    let goods = this.data.goodsList;
    let data = [];
    if (that.data.newvalue != 1) {
      wx.showToast({
        title: '请阅读协议后勾选下单',
        icon: 'none',
        duration: 1000
      })
      return false;
    }
    for (let i = 0; i < goods.length; i++) {
      let item = {};
      item.type = 1;
      item.id = goods[i].goodsid;
      item.unitprice = goods[i].price;
      item.number = goods[i].num;
      data.push(item)
    }
    if (that.data.consigneeid == "") {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    const param = {
      consigneeid: this.data.consigneeid,
      goodslist: JSON.stringify(data),
      goodstotalprice: totalPrice,
      invoicetaxprice: 0,
      orderprice: totalPrice,
      packingprice: 0,
      paymentprice: totalPrice,
      transportprice: 0,
      usebalance: 0,
      usecoin: checkedcoin ? maxPrice : 0
    }
    app.request({
      url: "shopp/goodsOrderApi/submitGoodsOrder",
      data: param,
      success: function(res) {
        that.invoice(res.data.orderid);
        let { ifPayment, orderid } = res.data;
        if (ifPayment) {
          wx.navigateTo({
            url: '../user-shop-goods-order-pay/user-shop-goods-order-pay?res=' + orderid + '&totalMoney=' + calculateTotalMoney + "&payType=1" + '&orderType=2',
          });
        } 
        if (ifPayment == 0) {
          let { actualBalance } = res.data;
          wx.navigateTo({
            url: "../doctor-course-payEnd/doctor-course-payEnd?orderid=" + res.data.orderid + "&beautyCoin=" + that.data.maxCoin +"&payType=1"
          });
        }
      },
      fail: function(res) {}
    });
  },
  address() {
    var that = this;
    wx.navigateTo({
      url: '../address-list/address-list',
    })
  },
  //发票信息
  invoice(orderid) {
    if (this.data.invoice) {
      const param = {
        orderNumber: orderid,
        orderType: this.data.orderType,
        headType: this.data.invoice.headType,
        headName: this.data.invoice.headName || '',
        identityNumber: this.data.invoice.identityNumber || ''
      };
      app.request({
        url: 'shopp/financeApi/insertInvoice',
        data: param,
        success: function (res) { },
        fail: function (res) { }
      });
    }
  } 
})